# coding=utf-8
import cv2
import PickBlue


def getMost(array):
    max_cnt = 0
    most_num = 0
    for i in range(len(array)):
        cnt = 0
        for j in range(len(array)):
            if array[i] * 0.8 <= array[j] <= array[i] * 1.2:
                cnt += 1
        #         print(array[j], array[i])
        # print("-----------", cnt)
        if cnt > max_cnt:
            max_cnt = cnt
            most_num = array[i]
    sum = 0
    # print("most_num", most_num)
    among = False
    start_pos = 0
    max_gap = 0
    max_start_pos = 0
    max_end_pos = 0
    for i in range(len(array)):
        if most_num * 0.8 <= array[i] <= most_num * 1.2:
            sum += array[i]
            # print("sum: ", sum)
            # print("i: ", i)
            if not among:
                among = True
                start_pos = i
        else:
            if among:
                among = False
                if max_gap < i - start_pos:
                    max_gap = i - start_pos
                    max_start_pos = start_pos
                    max_end_pos = i
    if among:
        if max_gap < len(array) - start_pos:
            max_start_pos = start_pos
            max_end_pos = len(array) - 1
    print("一行的平均高度：", sum/max_cnt, max_cnt)
    print("基准位置：", max_start_pos)
    return sum/max_cnt, max_start_pos, max_end_pos


def split(a, height, width):  # 获取各行起点和终点
    # for i in range(len(a)):
    #     if a[i] < width / 20:
    #         a[i] = 0
    start = []
    end = []
    length = []
    gap = []
    if a[0] != 0:
        start.append(0)
    for i in range(len(a)-1):
        if a[i] == 0 and a[i+1] > 0:
            start.append(i)
        if a[i+1] == 0 and a[i] > 0:
            end.append(i)
    if a[-1] > 0:
        end.append(len(a)-1)
    print("start_origin:", start)
    print("end_origin:", end)
    for i in range(len(start)):
        length.append(end[i] - start[i])
    for i in range(len(start)-1):
        gap.append(start[i+1]-end[i])
    print("length:", length)
    print("gap:", gap)
    length_gap,  length_right_start_pos, length_right_end_pos = getMost(length)
    print("正确的开始和结束", length_right_start_pos, length_right_end_pos)
    # gap_gap = sum(gap[length_right_start_pos:length_right_end_pos-1]) / (length_right_end_pos - length_right_start_pos-1)
    print(gap[length_right_start_pos:length_right_end_pos])
    print(length_right_end_pos - length_right_start_pos)
    # print("行间间隔", gap_gap)

    # new_start = []
    # new_end = []
    # now = start[length_right_start_pos]
    #
    # while now - (length_gap + gap_gap) > 0:
    #     now -= length_gap + gap_gap
    #
    # while now + length_gap < height:
    #     new_start.append(int(now+0.5))
    #     new_end.append(int(now + length_gap+0.5))
    #     now += length_gap + gap_gap
    #
    # print("cal_start:", new_start)
    # print("cal_end:", new_end)
    for i in range(len(length)):
        start[i] = int(max(0, start[i]-0.5*max(0, length_gap-length[i])-1))
        end[i] = int(min(height, end[i]+0.5*max(0, length_gap-length[i])+1))
    return start, end


def get_horizontal_shadow(img, img_bi):  # 水平投影+分割
    # 1.水平投影
    h, w = img_bi.shape[:2]
    shadow_h = img_bi.copy()  # shadow_h画图用(切记！copy后面还有个())

    a = [0 for z in range(0, h)]  # 初始化一个长度为h的数组，用于记录每一行的黑点个数

    for j in range(0, h):  # 遍历一行
        for i in range(0, w):  # 遍历一列
            if shadow_h[j, i] == 0:  # 发现黑色
                a[j] += 1  # a数组这一行的值+1
                shadow_h[j, i] = 255  # 记录好了就变为白色

    for j in range(0, h):  # 遍历一行 画黑条,长度为a[j]
        for i in range(0, a[j]):
            shadow_h[j, i] = 0
    cv2.imshow("line", shadow_h)
    cv2.imwrite("cutLines/" + "line.jpg", shadow_h)
    return a


def character_cut(img, img_bi, height, width):
    res = []
    ha = get_horizontal_shadow(img, img_bi)
    h_star, h_end = split(ha, height, width)
    for i in range(len(h_star)):
        hs, he = h_star[i], h_end[i]
        if hs != he:
            img_line = img[hs:he, 0:img.shape[1]]
            res.append(img_line)
    return res


def wordCut(img):
    print("对单张票据进行文本行切割")
    h, w = img.shape[:2]
    line_img = img.copy()

    border_img = cv2.Canny(img, 50, 150)
    bh, bw = border_img.shape[:2]
    for j in range(bh):
        for k in range(bw):
            border_img[j][k] = 255 - border_img[j][k]
    border_img = PickBlue.dilate_demo(border_img, 2)

    for i in range(0, h):
        for j in range(0, w):
            B = float(img[i][j][0])
            G = float(img[i][j][1])
            R = float(img[i][j][2])
            if (B / max(G + R + B, 1)) * 255 > 86 or R + G + B < 240:
                area_sum = 0
                canny_sum = 0
                for x in range(i - 2, i + 2, 1):
                    for y in range(j - 2, j + 2):
                        if x < h and y < w:
                            area_sum += 1
                            if border_img[x, y] == 0:
                                canny_sum += 1
                if canny_sum / area_sum < 0.7:
                    line_img[i][j] = [255, 255, 255]
                else:
                    line_img[i][j] = [0, 0, 0]
            else:
                line_img[i][j] = [255, 255, 255]

    line_img = cv2.cvtColor(line_img, cv2.COLOR_BGR2GRAY)
    # border_img = cv2.Canny(cv2.GaussianBlur(img, (5, 5), 0), 50, 150)
    # for i in range(h):
    #     for j in range(w):
    #         border_img[i][j] = 255 - border_img[i][j]
    cv2.imshow("line_img", line_img)
    cv2.imwrite("cutLines/" + "line_img.jpg", line_img)
    return character_cut(img, line_img, h, w)
